/**
 * Jquery ready
 * some event click, change ,...
 *
 * @author hungtd <hungtd@vng.com.vn>
 */

function __cfg(c) {
    return(cfg && cfg.cfg && cfg.cfg[c]) ? cfg.cfg[c]: false;
}

(jQuery);
jQuery('html').addClass('js');
jQuery(document).ready(function($) {	
	// disable right click
//	$(this).bind("contextmenu", function(e) {
//        e.preventDefault();
//    });

    // go to top
    jQuery("#BoxRight").addScrollControl({
        initTop : 350,
        offsetTop : 350,
        animation : false,
        offsetToScroll : 0,
        offsetLeft : 970,
        RelativeID : "MainHome"
    });	
	
	// new ticker
	$('#notes-home-page').newsticker();
	
    // UI select
    if (jQuery(".SelectUI").length > 0) {      
        jQuery(".SelectUI").addSelectUI({
            scrollbarWidth: 10 //default is 10
        });
    }
    
    if (jQuery(".SelectFrom").length > 0) {
        jQuery(".SelectFrom").addSelectUI({
            scrollbarWidth: 10 //default is 10
        });
    }
    
    // hide choose children deal
    $('body').livequery('click', function(e) {            
        $('.JsBuyDealShowChildrenDeal').hide();
    });
	
	// foverlabel
	$('form .JsOverLabel label').overlabel();
	
	// datepicker
	$('form .JsDateTime').fdatepicker();
    
    // time picker
    $('.JsTimePicker').livequery(function() {
        $(this).timePicker();
    });
	
	// parent load ajax
	$('.JsRequest a').livequery('click', function() {
        $this = $(this);		            
        var aurl = $this.attr('href');
		$('.JsResponse').load(aurl);
        return false;
    });
	
	// a load ajax
	$('a.aAjax').livequery('click', function() {
        $this = $(this);		            
        var aurl = $this.attr('href');
		$('.JsResponse').load(aurl);
        return false;
    });
	
	// show tab
	$('.JsTabA li a').livequery('click', function() {
		$this = $(this);
		$('.JsTabA li').removeClass('Active');
		$this.parent().addClass('Active');
	});
	
	// quick login
	$('.JsQuickLogin').livequery('click', function() {showFormQuickLogin();});		
	
    // count down
    $('.js-deal-end-countdown, .js-deal-end-countdown-2').livequery(function() {
        //var end_date = parseInt($(this).parents().find('.js-time').html());
        var end_date = $(this).parents().find('.js-time').html();
        $(this).countdown( {
            until: strToOjectDate(end_date),
            format: 'H M S'
        });
    });
	
    // charge 
    $('.quick-payment-submit').livequery('click', function () {
        return ChargeCard();
    });
	
    // charge IB
    $('#ZingTransactionAmount').livequery('keyup', function()
    {
        $('#ZingTransactionAmount').val(formatCurrency( $('#ZingTransactionAmount').val()));
        // get amount int
        var amount = parseInt($('#ZingTransactionAmount').val().replace(/\$|\,/g,''));
        // get config promotion
        var discount_percent = parseInt($('#promotion-ib-discountpercent').val());
        var min_amount = parseInt($('#promotion-ib-minamount').val());
        // check not promotion
        if (discount_percent < 0 || amount < min_amount) {
            $('#ib-discount-amount').html('0');
            $('#ib-discounted-amount').html(formatCurrency($('#ZingTransactionAmount').val()));
            $('#ib-pay-amount').html(formatCurrency($('#ZingTransactionAmount').val()));
        } else {
            var discount_amount = (amount * discount_percent) / 100;
            var discounted_amount = amount - discount_amount;
            $('#ib-discount-amount').html(formatCurrency(discount_amount));
            $('#ib-discounted-amount').html(formatCurrency(discounted_amount));
        }
    });
	
    // submit click IB
    $('.js-submit-button-banking').livequery('click', function()
    {
        if (!checkIB()) {
            return false;
        }
    });
	
    // user Buy
    // check amount when user change quantity
    $('.js-quantity li').livequery('click', function() {
        var new_amount = parseFloat(parseInt($(this).attr('value')) * parseFloat($('#DealDealAmount').val()));
        new_amount = isNaN(new_amount) ? 0: new_amount;
        /* HUNGTD format currency */
        var zingdeal_format_currency = formatCurrency(new_amount);        
        $('.js-deal-total').html(zingdeal_format_currency);
		$('.DealBuyQuantityPopup').html($(this).attr('value'));
		$('.DealBuyTotalAmountPoupup').html(zingdeal_format_currency);
		if ($('#DealPaymentTypeId6:checked').val() == 6) {			
			CODConfirm();			
		}
        return false;
    });   
	
    // change payment method to COD
    $('#DealPaymentTypeIdTmp6').livequery('click', function () {
		$('#DealPaymentTypeId6').attr('checked', true);
    	$('.TabOption li').removeClass('Active');
    	$(this).parent().parent().addClass('Active');
    	CODConfirm();
    });
	
	// set default
    if ($('#DealPaymentTypeId4').val() == 4) {
        $('#DealPaymentTypeId4').attr('checked', true);
        $('#DealPaymentTypeIdTmp4').attr('checked', true);
    } else if ($('#DealPaymentTypeId6').val() == 6) {
        $('#DealPaymentTypeId6').attr('checked', true);
        $('#DealPaymentTypeIdTmp6').attr('checked', true);
        CODConfirm();
    }
	$('#DealQuantity').val(1);
	
    // change payment method to Zing Xu		
    $('#DealPaymentTypeIdTmp4').livequery('click', function () {
		$('#DealPaymentTypeId4').attr('checked', true);
    	$('.TabOption li').removeClass('Active');
    	$(this).parent().parent().addClass('Active');
		ShowHideDiv('.JsZingXuMethod', '.JsCODMethod');		
    	$('.JsCODMethod').children().remove();        
    });
	
    // user click buy
    $('.js-buy-confirm').livequery('click', function () {
		// check xem user da login hay chua.
		// neu user chua login hien popup login nhanh
		if(isUserLogin()) {
			if ($('#DealPaymentTypeId6:checked').val() == 6) {			
				if (checkCODAddress() == 1) {
					var is_confirm_cod = $('#isConfirmCOD').val();
					if (is_confirm_cod == 1) {
						var aurlpopup = __cfg('path_relative') + 'delivery_addresses/popup_confirm'+'/cache:'+Math.floor(Math.random()*10000);
						PopUpZD(aurlpopup, 1);
					} else {
						//AddDeliveryAddressNotConfirm();
                        PopUpZD($('.AlertBuyDealCOD').html(), 0);
					}
				}			
	    	} else if ($('#DealPaymentTypeId4:checked').val() == 4) {
                if ($('#DealIsGift').val() == 1) {
                    $('.DealBuyQuantityPopup').html($('#JsBuyGiftFriendQuantity').val());
                    var giftQuantity = parseInt($('.DealBuyQuantityPopup').html());
                    var giftAmount = giftQuantity*parseFloat($('#DealDealAmount').val());
                    $('.DealBuyTotalAmountPoupup').html(giftQuantity);
                    $('.DealBuyTotalAmountPoupup').html(formatCurrency(giftAmount));
                }
                if (parseInt($('.DealBuyQuantityPopup').html()) > 0)
                    PopUpZD($('.AlertBuyDealZingXu').html(), 0);
                else
                    AlertZingDeal(JsLangZD.alert_choose_quantity);
	    	}
		} else { 
	    	showFormQuickLogin();
		}
    	return false;
    });	
	
	// user view buy gift for friend	
	$('#JsBuyGiftAddFriend').livequery('click', function() {
		// check data
		if (checkGiftForm() == false) return false;		
		// get data input
		var giftFrom = $('input[name=Jsgift_from]').val();
		var giftQuantity = $('select[name=Jsquantity]').val();
		var giftTo = $('input[name=Jsgift_to]').val();
		var giftMail = $('input[name=Jsgift_mail]').val();
		var giftPhone = $('input[name=Jsgift_phone]').val();
		var giftMessage = $('textarea[name=Jsmessage]').val();
		var dataInput = giftFrom + '|' + giftQuantity + '|' + giftTo + '|' + giftMail + '|' + giftPhone + '|' + giftMessage;
		// add friend count
		var cQuantity = parseInt($('#JsBuyGiftFriendQuantity').val());
		var addQuantity = cQuantity + parseInt(giftQuantity);
		var maxQuantity = parseInt($('#max_info_number').val());
		// check quantity
		if (addQuantity <= maxQuantity) {
			$('#JsBuyGiftFriendQuantity').val(addQuantity);
		} else {
			return false;
		}						
		// add item to cart		
		// get quanti ty
		var quantity = parseInt($('select[name=Jsquantity]').val());
		// get price item
		var sPrice =  $('.Box-VoucherMain .TitleVoucher .Box-Voucher .Voucher .cr').html();
		var dPrice = parseFloat(sPrice.toString().replace(/\$|\,/g,''));
		var tdPrice = (dPrice * quantity);
		var tPrice = formatCurrency(tdPrice);
		// get current totla price
		var sShowPrice = $('.js-deal-total').html();
		var dShowPrice = parseFloat(sShowPrice.toString().replace(/\$|\,/g,''));
		var showPrice = tdPrice + dShowPrice;		
		// html row
		var rowCart = '<tr class="OddRow OddRowViDeal">';		
		rowCart += '<td class=" VeztTop">' + $('.Box-VoucherMain .TitleVoucher p').html() + '</td>';
		rowCart += '<td class="HorzCenter VeztTop JsBuyGiftRowQuantity">' + quantity + '</td>';
		rowCart += '<td class="HorzCenter VeztTop">' + sPrice + '</td>';
		rowCart += '<td  class="HorzCenter VeztTop JsBuyGiftRowtPrice">' + tPrice + '</td>';
		rowCart += '<td  class="HorzCenter VeztTop"><a href="javascript:void(0)" class="JsBuyGiftDelRow"> </a></td>';
		rowCart += '<td class="hide"><textarea name="buy_gift_info_friend[]" class="hide">' + dataInput + '</textarea></td></tr>';
		$('#JsBuyGiftCart').append(rowCart);    	
		// add current price
		$('.js-deal-total').html(formatCurrency(showPrice));
	});	 
	// remove friend in buy gift
	$('a.JsBuyGiftDelRow').livequery('click', function () {
		var dQuantity = $(this).parent().parent().children('.JsBuyGiftRowQuantity').html();
		var cQuantity = parseInt($('#JsBuyGiftFriendQuantity').val());
		var addQuantity = cQuantity - parseInt(dQuantity);
		$('#JsBuyGiftFriendQuantity').val(addQuantity);
		// remove
		$(this).parent().parent().remove();			
		// get current price
		// get this row price
		var sRowPrice = $(this).parent().parent().children('.JsBuyGiftRowtPrice').html();
		var dRowPrice = parseFloat(sRowPrice.toString().replace(/\$|\,/g,'')); 		
		// get current totla price
		var sShowPrice = $('.js-deal-total').html();
		var dShowPrice = parseFloat(sShowPrice.toString().replace(/\$|\,/g,''));
		var showPrice = dShowPrice - dRowPrice;
		// add current price
		$('.js-deal-total').html(formatCurrency(showPrice));
	});
	
	// User Show Menu
	$('.JsUserMenu').livequery('click', function () {
		$('.userMenuRight').slideToggle();
	});
	
	// Search Transaction
	$('.JsTransactionSb').livequery('click', function () {
		var ride = $('input[name=rediosearchtmp]:checked').val();		
		if (ride == 'day') {
			location.replace($('#ztartday').val());
		} else if (ride == 'week') {
			location.replace($('#ztartweek').val());
		} else if (ride == 'month') {
			location.replace($('#ztartmonth').val());
		} else if (ride == 'all') {
			$('#ZingTransactionIndexForm').submit();
		}
	});
	
	// check balance Zing
	if ($('span').hasClass('JsBalance') == true) {getBalanceZing();}
	
	// remove iframe	
	$('#IfSSOLogin').contents().find('head').html('<title></title>');
	$('#IfSSOLogin').contents().find('body').html('<div></div>');	
	
	// hide popup 
	$('.JsCancel').livequery('click', function() {
		AlertHide();
	});			
		
	// show hide topic
	$('a.AnsView2').livequery('click', function() {
		$(this).hide();
		$(this).siblings('.AnsView1').show();			
	});
	$('a.AnsView1').livequery('click', function() {
		$(this).hide();
		$(this).siblings('.AnsView2').show();		
		$(this).parents('.BoxView1').children('.JsTopicContent').hide();	        
        $(this).parents('.BoxView2').children('.JsTopicContent').hide();        
	});
	
	// kiem tra tai khoan tren Zing Deal
	$('.JsCheckZingDealAccount').livequery('click', function() {
		$this = $(this);
		var inputUsername = $(this).siblings('input'); 
		checkAccountZingDeal(inputUsername);
	});
	
	// kiem tra tai khoan tren Zing ID
	$('.JsCheckZingIDAccount').livequery('click', function() {
		$this = $(this);
		var inputUsername = $(this).siblings('input'); 
		checkAccountZingID(inputUsername);
	});
	
	// reload captcha
	$('#contacts-add form a.js-captcha-reload, #users-register form a.js-captcha-reload').livequery('click', function() {
        captcha_img_src = $(this).parents('.js-captcha-container').find('.captcha-img').attr('src');
        captcha_img_src = captcha_img_src.substring(0, captcha_img_src.lastIndexOf('/'));
        $(this).parents('.js-captcha-container').find('.captcha-img').attr('src', captcha_img_src + '/' + Math.random());
        if ($('.js-captcha-input')) {
            $('.js-captcha-input').val('');
        }
        return false;
    });
	
	// check length password
	$('.JsPassword').livequery('keyup', function() {
		$this = $(this);
		// get pwd
		var pwd = $this.val();
		// kiem tra pwd
		// kiem tra pass co chu so hay khong
        re = /[0-9]/;
        if(!re.test(pwd)) chu_so = 0; else chu_so = 1;
        // kiem tra pass co chu thuong hay khong
        re = /[a-z]/;
        if(!re.test(pwd)) chu_thuong = 0; else chu_thuong = 1;
        // kiem tra pass co chu hoa hay khong
        re = /[A-Z]/;
        if(!re.test(pwd)) chu_hoa = 0; else chu_hoa = 1;
        // kiem tra pass cho ky tu dac biet hay khong
        re = /[\W_]/;
        if(!re.test(pwd)) ky_tu = 0; else ky_tu = 1;
		
		// total conditions
		tCondition = parseInt(chu_so) + parseInt(chu_thuong) + parseInt(chu_hoa) + parseInt(ky_tu);
		
		if (pwd.length >= 8 && tCondition >= 0) $('#meta1').addClass('meta'); else $('#meta1').removeClass('meta');		
		if (pwd.length >= 8 && tCondition >= 2) $('#meta2').addClass('meta'); else $('#meta2').removeClass('meta');
		if (pwd.length >= 8 && tCondition >= 3) $('#meta3').addClass('meta'); else $('#meta3').removeClass('meta');
		if (pwd.length >= 8 && tCondition >= 4) $('#meta4').addClass('meta'); else $('#meta4').removeClass('meta'); 		
	});
	
	// check pwd again
	$('.JsConfirmPassword').livequery('blur', function() {
		$this = $(this);
		if ($this.val() == $('.JsPassword').val()) $this.siblings('.Note').hide();
		else $this.siblings('.Note').show();
	});
	
	// check email
	$('.JsEmail').livequery('blur', function() {
		$this = $(this);
		if ($this.siblings('.Note').hasClass('empty')) if ($this.val() == '') return true;
		if (validateEmail($this.val())) $this.siblings('.Note').hide();
		else $this.siblings('.Note').show();
	});
	
	// check phone
	$('.JsPhone').livequery('blur', function() {
		$this = $(this);
		if ($this.siblings('.Note').hasClass('empty')) if ($this.val() == '') return true;
		if (validatePhone($this.val())) $this.siblings('.Note').hide();
		else $this.siblings('.Note').show();
	});
	
	// check empty
	$('.JsEmpty').livequery('blur', function() {
		$this = $(this);		
		if ($this.val()) $this.siblings('.Note').hide();
		else $this.siblings('.Note').show();
	});
	
	// show label deal category
	$('.JsDealCategoryTop ul li').livequery('mouseover', function() {
		$('.JsDealCategoryTop ul li a').show();
		$('.JsDealCategoryTop').removeClass('dc-nav-small');$('.JsDealCategoryTop').addClass('dc-nav-big'); 
	});
	// hide label deal category
	$('.JsDealCategoryTop ul li').livequery('mouseout', function() {
		$('.JsDealCategoryTop ul li a.DCLabel').hide();
		$('.JsDealCategoryTop').removeClass('dc-nav-big');$('.JsDealCategoryTop').addClass('dc-nav-small');
	});
	// change deal category when (window) resize small
	$(window).resize(function() {
		$this = $(this);		
		if ($this.width() <= 1100) $('.JsDealCategoryTop').addClass('dc-nav-slow');
		else $('.JsDealCategoryTop').removeClass('dc-nav-slow');
	});
	// change deal category when (window) small
	if ($(window).width() <= 1100) $('.JsDealCategoryTop').addClass('dc-nav-slow');
	else $('.JsDealCategoryTop').removeClass('dc-nav-slow');
	
	// recent deal searcj
	$('.JsRecentDealSearch').livequery('click', function() {
		var keyWord = $('#RecentDealSearchForm input[name=rdkeyword]').val();
		keyWord = encodeURI(keyWord);
		var from_date = $('#RecentDealSearchForm input[name=rdsdate_text]').val();		
		var to_date = $('#RecentDealSearchForm input[name=rdtdate_text]').val();		
		var ftimeSearch = toTimestamp(from_date);
		var ttimeSearch = toTimestamp(to_date);	
        var categoryid = $('#RecentDealSearchForm select[name=rdcategoryid]').val();
		var RURL = $('#RecentDealSearchForm input[name=URL_FormSearch]').val();
		var RSURL = (RURL + '/q:' + keyWord + '/sdate:' + ftimeSearch + '/edate:' + ttimeSearch + '/category:' + categoryid);
		window.location.href = RSURL;		
	});
    
    // show quick instruction
    $('.JsTitleQuickIntruction').livequery('click', function() {
        $this = $(this);
        if ($this.parent().hasClass('show')) {
            $('ul.Huongdan li').removeClass('show');
            $('p.JsQuickIntruction').hide();
        } else {
            $('ul.Huongdan li').removeClass('show');
            $this.parent().addClass('show');        
            $('p.JsQuickIntruction').hide();
            $this.siblings('p.JsQuickIntruction').show();
        }
    });
    
    // auto submit
    $('form select.js-admin-index-autosubmit').livequery('change', function() {
        if ($('.js-checkbox-list:checked').val() != 1 && $(this).val() >= 1) {
            alert('Please select atleast one record!');
            $(this).val('');
            return false;
        } else if ($(this).val() >= 1) {
            if (window.confirm('Bạn có chắc là thực hiện hành động này này?')) {
                $(this).parents('form').submit();
            } else {
                $(this).val('');
            }
        }
    });
    
    // choose City
    //$('#DealCitySelect').livequery('change', function () {
        //window.location.href = $(this).val();
    //});
    
    // change select to city defalt
    var ZDCITY = readCookie('CakeCookie[city_slug]');
    var JsCurrentCity = $('.'+ZDCITY).html();
    $('#province .DropListUI p').html(JsCurrentCity);
    //$('.'+ZDCITY).attr('selected', 'selected');
    $('.SelectFrom li').livequery('click', function() {
        window.location.href = $('#DealCitySelect').val();        
    });
    
    // count deal user when deal is hot deal
    if ($('strong').hasClass('JsQuantityDealUserCount')) {        
        var aurl=__cfg('path_relative')+'ajaxpages/deal_countbought/'+$('#JsDealViewDealId').html()+'/cache:'+Math.floor(Math.random()*10000);
        $('.JsQuantityDealUserCount').load(aurl);
    }
    
    // show list subdeal
    $('.JsShowChildrenDeal').livequery('click', function(e) {
        $this = $(this);
        var is_gift;
        if ($this.hasClass('JsDealBuyGift')) {is_gift = 1;} else {is_gift = 0}
        var dealID = $this.siblings('.JsDealId').html();
        var aurl=__cfg('path_relative')+'ajaxpages/show_childrendeal/'+dealID+'/'+is_gift+'/1'+'/cache:'+Math.floor(Math.random()*10000);
        PopUpZD(aurl, 1);
        e.preventDefault();
        return false;
    });    
    
    // show choose other children deal
    $('.JsBuyDealShowChooseDeal').livequery('click', function(e) {
        var deal_id = $('input[name=JsBuyDealId]').val();
        chooseOtherChildrenDeal(deal_id);
        e.stopPropagation();
    });        
    
    // tip for sub deal
    $('a.fixedTip').livequery(function(){
        var tip = $(this).siblings('.JsTooltipContent').html();
        $(this).aToolTip({
            fixed: false,
            xOffset: 10,
    		yOffset: -80,            
            tipContent: tip            
        });
    });
	
    // get ward for COD
    $('#DADistrictId').livequery('change', function() {
        $this = $(this);
        var aurl = __cfg('path_relative')+'district_wards/index/' + $this.val() + '/cache:'+Math.floor(Math.random()*10000);
        $('#DAWard').load(aurl);
    });
});
// end jQuery
if (getCookie('ice') == '') {
    document.cookie = 'ice=true;path=/';
}